package com.eostoken.eos_wallet.ui.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.MapUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseActivity;
import com.eostoken.eos_wallet.bean.GetBindWalletAddressBean;
import com.eostoken.eos_wallet.bean.MsgCodeBean;
import com.eostoken.eos_wallet.db.MgpWallet;
import com.eostoken.eos_wallet.helper.DialogConfirmListener;
import com.eostoken.eos_wallet.helper.DialogHelper;
import com.eostoken.eos_wallet.mvp.mode.AppsModel;
import com.eostoken.eos_wallet.mvp.presenter.AppsPresenterImpl;
import com.eostoken.eos_wallet.mvp.view.AppsView;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.RSAUtils;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.qmuiteam.qmui.layout.QMUIRelativeLayout;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.eostoken.eos_wallet.utils.Constants.BIND_ADDRESS;
import static com.eostoken.eos_wallet.utils.Constants.CHECK_ADDR;
import static com.eostoken.eos_wallet.utils.Constants.GET_BIND_ADDRESS;

public class BindWalletActivity extends BaseActivity<AppsModel, AppsView, AppsPresenterImpl> implements AppsView {

    @BindView(R.id.topBar)
    QMUITopBar topBar;
    @BindView(R.id.walletIconTv)
    QMUIRadiusImageView walletIconTv;
    @BindView(R.id.walletNameTv)
    AppCompatTextView walletNameTv;
    @BindView(R.id.walletAccountTv)
    AppCompatTextView walletAccountTv;
    @BindView(R.id.walletInfoLayout)
    QMUIRelativeLayout walletInfoLayout;
    @BindView(R.id.bindAddressEt)
    AppCompatEditText bindAddressEt;
    @BindView(R.id.nextstepBtn)
    QMUIRoundButton nextstepBtn;


    private String accountName;
    private MgpWallet wallet;
    private int mRadius;
    private MsgCodeBean msgCodeBean;
    private QMUIDialog qmuiDialog;

    @Override
    public int getContentView() {
        return R.layout.activity_bind_wallet;
    }

    @Override
    protected void initData() {
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_color_blue));
        BarUtils.setStatusBarLightMode(this, false);
        wallet = WalletUtils.getCurrentWallet(this);
        accountName = wallet.getCurrentAccountName();
        mRadius = QMUIDisplayHelper.dp2px(this, 8);
        getBindWalletAddress();
    }

    @Override
    public void initView() {
        topBar.setTitle(getString(R.string.str_bind_eth_address));
        topBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        walletInfoLayout.setRadius(mRadius);
        walletNameTv.setText(wallet.getWalletName());
        walletAccountTv.setText(accountName);

    }

    @OnClick(R.id.nextstepBtn)
    public void onViewClicked() {
        if (ObjectUtils.isEmpty(bindAddressEt.getText())) {
            ToastUtils.showLong(R.string.str_please_enter_eth_address);
        } else {
            if (qmuiDialog == null) {
                qmuiDialog = DialogHelper.showEditTextDialog(BindWalletActivity.this, getString(R.string.str_password_authentification),
                        getString(R.string.str_enter_password), getString(android.R.string.ok), getString(android.R.string.cancel), listener, true);
            }
            qmuiDialog.show();
        }
    }

    DialogConfirmListener listener = new DialogConfirmListener() {
        @Override
        public void onClick(QMUIDialog dialog, View view, int index) {
            dialog.dismiss();
            EditText editText = (EditText) view;
            String contrastPassword = editText.getText().toString().trim();
            if (ObjectUtils.equals(contrastPassword, wallet.getWalletPassword())) {
                checkAddr();
            } else {
                ToastUtils.showShort(StringUtils.getString(R.string.str_wrong_password));
            }
            editText.setText("");
        }
    };

    @Override
    public void updateView(Object data, int responseSuccessCode) {
        if (data != null) {
            switch (responseSuccessCode) {
                case GET_BIND_ADDRESS:
                    msgCodeBean = GsonUtils.fromJson(data.toString(), MsgCodeBean.class);
                    if (msgCodeBean != null) {
                        //备注: 0绑定成功 1绑定中 2 需绑定 3 错误信息(直接弹出)  5暂未开启
                        if (msgCodeBean.getCode() == 0) {
                            nextstepBtn.setVisibility(View.GONE);
                            bindAddressEt.setText(msgCodeBean.getMsg());
                            setEditableEditText(bindAddressEt, false);
                        } else {
                            nextstepBtn.setVisibility(View.VISIBLE);
                            setEditableEditText(bindAddressEt, true);
                        }
                    }
                    break;
                case BIND_ADDRESS:
                    MsgCodeBean msgCodeBean = GsonUtils.fromJson(data.toString(), MsgCodeBean.class);
                    if (msgCodeBean != null) {
                        if (msgCodeBean.getCode() == 0) {
                            ToastUtils.showLong(R.string.str_binding_succeed);
                            finish();
                        } else {
                            ToastUtils.showLong(msgCodeBean.getMsg());
                        }

                    }
                    break;
                case CHECK_ADDR:
                    if (ObjectUtils.isNotEmpty(data)) {
                        MsgCodeBean msgCodeBean1 = GsonUtils.fromJson(data.toString(), MsgCodeBean.class);
                        if (msgCodeBean1 != null) {
                            if (msgCodeBean1.getCode() == 2) {
                                bindAddress();
                            } else {
                                ToastUtils.showLong(msgCodeBean1.getMsg());
                            }
                            break;
                        }
                    }
                    ToastUtils.showLong(R.string.str_binding_failure);
                    break;
            }
        }
    }

    @Override
    public void onFailure(Object data, int responseFailCode) {
        switch (responseFailCode) {
            case GET_BIND_ADDRESS:
                break;
            case BIND_ADDRESS:
            case CHECK_ADDR:
                ToastUtils.showLong(R.string.str_binding_failure);
                break;
        }
    }

    @Override
    public void updateView(boolean success, Object o1, Object o2) {
        if (success) {
            if (ObjectUtils.isEmpty(o1)) {
                ToastUtils.showLong(R.string.str_binding_failure);
            } else {
                bindWalletAddress(o1.toString());
            }
        } else {
            ToastUtils.showLong(R.string.str_binding_failure);
        }
    }

    @Override
    public AppsModel createModel() {
        return new AppsModel();
    }

    @Override
    public AppsView createView() {
        return this;
    }

    @Override
    public AppsPresenterImpl createPresenter() {
        return new AppsPresenterImpl(this);
    }

    @Override
    public boolean isShowState() {
        return true;
    }

    public void setEditableEditText(AppCompatEditText editText, boolean isEnabled) {
        editText.setEnabled(isEnabled);//去掉点击时编辑框下面横线:
        editText.setFocusable(isEnabled);//不可编辑
        editText.setFocusableInTouchMode(isEnabled);//不可编辑
    }

    private void getBindWalletAddress() {
        try {
            Map params = MapUtils.newHashMap();
            params.put("currentAddr", accountName);
            params.put("type", "2");
            String jsonData2 = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData2);
            presenter.requestPortData(content, GET_BIND_ADDRESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void bindAddress() {
        try {
            String bindAddress = bindAddressEt.getText().toString().trim();
            Map params = MapUtils.newHashMap();
//            params.put("currentAddr", accountName);
//            params.put("bindAddr", bindAddress);
//            params.put("type", "2");
//            String jsonData2 = GsonUtils.toJson(params);
//            String content = RSAUtils.encrypt(jsonData2);
            String action = "bindaddress";
            String privateKey = wallet.getPrivateKey();
            params.put("account", accountName);
            params.put("address", bindAddress);
            String jsonData = GsonUtils.toJson(params);
            presenter.sendTransaction(action, privateKey, accountName, Constants.contractAddress, jsonData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void bindWalletAddress(String hash) {
        try {
            String bindAddress = bindAddressEt.getText().toString().trim();
            Map params = MapUtils.newHashMap();
            params.put("currentAddr", accountName);
            params.put("bindAddr", bindAddress);
            params.put("hash", hash);
            params.put("type", "2");
            params.put("money", "0");
            String jsonData2 = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData2);
            presenter.requestPortData(content, BIND_ADDRESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkAddr() {
        try {
            String bindAddress = bindAddressEt.getText().toString().trim();
            Map params = MapUtils.newHashMap();
            params.put("address", accountName);
            params.put("bindAdress", bindAddress);
            params.put("type", "2");
            String jsonData2 = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData2);
            presenter.requestPortData(content, CHECK_ADDR);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
